<template>
  <div>
    <!-- 新建档案盒 -->
    <el-card class="box-card" :body-style="{ padding: 10 }">
      <el-form :inline="true" :model="queryParam" class="demo-form-inline" size="medium">
        <el-form-item label="盒号/盒名">
          <el-input v-model="queryParam.boxNoOrName" placeholder="请输入盒号或盒名" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否已发标签">
          <el-select v-model="queryParam.rfidFlag" placeholder="请选择" clearable>
            <el-option v-for="item in [
              { value: 0, label: '是' },
              { value: 1, label: '否' },
            ]" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="rest">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- </el-col> -->
      <el-row :gutter="24">
        <el-col :span="12">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="medium">新增档案盒</el-button>
          <el-button link @click="downTemplate">下载模板</el-button>
          <el-tooltip content="先下载导入模板，使用模板进行导入" placement="top" effect="light">
            <el-button link @click="importExcel">批量导入</el-button>
          </el-tooltip>
          <input ref="excelUploadInput" type="file" accept=".xlsx, .xls" style="display: none" @change="uploadChange" />
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button size="medium" type="danger" icon="el-icon-delete" @click="delBacth">删除</el-button>
          <el-button size="medium" type="primary" @click="sendTags">发标签</el-button>
          <el-button size="medium" type="primary" @click="goUp">去上架</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="box-card" :body-style="{ padding: 10 }">
      <SortableTable v-if="tableProps.length > 0" :table-props="tableProps" @update="UpdateTable">
      </SortableTable>
      <el-table :data="tableData" row-key="labelId" border style="width: 100%; overflow-y: auto" height="50vh"
        ref="table" @selection-change="handleSelectionChange" @sort-change="sortChange">
        <el-table-column type="selection" width="55" align="center" sortable> </el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center" sortable>
        </el-table-column>
        <el-table-column v-for="item of tableProps" :key="item.props" :prop="item.prop" :label="item.title"
          :width="item.width" :sortable="item.sortable" :show-overflow-tooltip="item.showOverflowTooltip">
          <template #default="scope">
            <span v-if="item.prop === 'boxNo'">
              <el-link type="primary" :underline="false" style="font-size: 12px" @click="archivesByBoxNo(scope.row)">
                {{ scope.row[item.prop] }}
              </el-link>
            </span>
            <span v-else-if="item.prop === 'stageStatus'">
              <el-tag v-show="scope.row.stageStatus == 0">未上架</el-tag>
              <el-tag v-show="scope.row.stageStatus == 1" type="success">已上架</el-tag>
              <el-tag v-show="scope.row.stageStatus == 2" type="danger">已下架</el-tag>
            </span>
            <span v-else-if="item.prop === 'storeStatus'">
              <el-tag v-show="scope.row.storeStatus == 0">未入库</el-tag>
              <el-tag v-show="scope.row.storeStatus == 1" type="success">在库</el-tag>
              <el-tag v-show="scope.row.storeStatus == 2" type="danger">离库</el-tag>
            </span>
            <span v-else>
              <span v-if="dictProps.map((dict) => dict.fieldName).includes(item.prop)">
                {{ getDictItemValue(item.prop, scope.row[item.prop]) }}
              </span>
              <span v-else>{{ scope.row[item.prop] }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150">
          <template slot-scope="{ row }">
            <el-button icon="el-icon-edit" link size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-popconfirm class="button10Left" title="确定要删除吗？" @confirm="() => handleDel(row)">
              <el-button slot="reference" icon="el-icon-delete" link size="mini" class="danger_button">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="box-card" :body-style="{ padding: 10 }">
      <pagination ref="pagination" :totalCount="totalCount" @pagination="pagination"></pagination>
    </el-card>
    <new-box-dialog ref="newBoxDialog" @ok="loadData"></new-box-dialog>
    <archives-by-box-no ref="archivesByBoxNo"></archives-by-box-no>
    <import-one-dialog ref="importOneDialog" @nextStep="importTwo" @close="closeImportOne"></import-one-dialog>
    <import-two-dialog ref="importTwoDialog" @ok="loadData" @close="closeImportTwo"
      :excelData="excelData"></import-two-dialog>
    <send-tags-dialog ref="sendTagsDialog" @ok="loadData" :field="field"></send-tags-dialog>
  </div>
</template>

<script>
import { newBoxPage, del, batchDel, templateBox, impBoxStep1 } from '@/api/rfid/label'
import { rfidAccountFieldDefinelistBox, resetDefaultBoxFieldSort } from '@/api/sys/field'
import { queryBoxTemp } from '@/api/sys/template'
import { getDictItemsByCodes } from '@/api/sys/dict'
import newBoxDialog from './dialog/newBoxDialog.vue'
import archivesByBoxNo from './dialog/archivesByBoxNo.vue'
import importOneDialog from './dialog/importOneDialog.vue'
import importTwoDialog from './dialog/importTwoDialog.vue'
import sendTagsDialog from './dialog/sendTagsDialog.vue'
export default {
  name: 'newBox',
  components: {
    newBoxDialog,
    archivesByBoxNo,
    importOneDialog,
    importTwoDialog,
    sendTagsDialog,
  },
  data() {
    return {
      totalCount: 0, //总数
      //查询条件
      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },
      queryParam: {},
      tableData: [],
      tableProps: [],
      dictProps: [],
      dictItems: {},
      selectionData: [],
      field: null,
      excelData: {
        data: null,
        props: null,
      },
    }
  },

  created() {
    this.getBoxFields()
  },

  methods: {
    toCamelCase(str) {
      // 首先将字符串分割成单词数组
      const words = str.split(/[-_\s]+/)

      // 如果字符串为空，返回空字符串
      if (words.length === 0) {
        return ''
      }

      // 将第一个单词小写，其余单词首字母大写，然后连接它们
      return (
        words[0].toLowerCase() +
        words
          .slice(1)
          .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
          .join('')
      )
    },
    getBoxFields() {
      rfidAccountFieldDefinelistBox()
        .then((res) => {
          if (res.data.code === 200) {
            this.tableProps = res.data.data.map((item) => {
              return {
                ...item,
                title: item.fieldTitle,
                prop: this.toCamelCase(item.fieldName),
                width: '',
                checked: true,
                showOverflowTooltip: true,
              }
            })
            // 将res.data.data中dictCode不为null的提取出来，生成一个对象数组，对象中包含fieldName和dictCode
            this.dictProps = res.data.data
              .filter((item) => item.dictCode !== null && item.dictCode !== '')
              .map((item) => {
                return {
                  fieldName: this.toCamelCase(item.fieldName),
                  dictCode: item.dictCode,
                }
              })
            if (this.dictProps.length > 0) {
              const dictCodes = this.dictProps.map((item) => item.dictCode)
              this.getDictItems(dictCodes)
            }
            this.loadData()
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    // 根据字典编码数组获取字典值
    getDictItems(dictCodes) {
      getDictItemsByCodes(dictCodes)
        .then((res) => {
          if (res.data.code === 200) {
            this.dictItems = res.data.data
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    getDictItemValue(fieldName, value) {
      // 在dictProps中获取对象
      const dictItem = this.dictProps.find((item) => item.fieldName === fieldName)
      // 查询dictItem.dictCode对应的字典值
      return this.dictItems[dictItem.dictCode]?.find((item) => item.value === value)?.label
    },
    async UpdateTable(tableProps) {
      // this.tableProps = this.onUpdateTable(tableProps)

      const AfterTable = tableProps.map((item, index) => {
        return {
          defineId: item.defineId,
          title: item.title,
          fieldSort: index,
        }
      })
      const { data } = await resetDefaultBoxFieldSort(AfterTable)
      if (data.code == 200) {
        this.tableProps = this.onUpdateTable(tableProps)
      } else {
        this.$message.error(data.message)
      }
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    sortChange({ column, prop, order }) {
      this.queryParam.sortField = prop
      this.queryParam.sortOrder = order
      this.loadData()
    },
    onSubmit() {
      this.$refs.pagination.resetPagination()
    },
    rest() {
      this.queryParam = {}
      this.$refs.pagination.resetPagination()
    },
    loadData() {
      var param = Object.assign(this.queryParam, this.searchModel)
      newBoxPage(param)
        .then((res) => {
          if (res.data.code === 200) {
            this.tableData = res.data.data.records
            this.totalCount = res.data.data.total
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    pagination(val) {
      this.searchModel.pageNo = val.page
      this.searchModel.pageSize = val.limit
      this.loadData()
    },
    handleDel(row) {
      del(row.labelId)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.loadData()
          } else {
            this.$message.warning(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    delBacth() {
      if (this.selectionData.length == 0) {
        this.$message.warning('请选择要删除的档案盒')
        return
      }
      this.$confirm('此操作将永久删除该档案盒, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const labelIds = this.selectionData.map((item) => item.labelId).join(',')
          batchDel(labelIds, 1).then((res) => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.loadData()
            } else {
              this.$message.warning(res.data.message)
            }
          })
        })
        .catch((error) => {
          if (error === 'cancel') {
            // 用户点击了取消按钮，可以在此处添加相应处理逻辑
          } else {
            // 其他错误情况，例如网络错误等
            this.$message.error(error)
          }
        })
    },
    downTemplate() {
      templateBox()
        .then((res) => {
          // 创建一个新的URL代表指定的File对象或Blob对象
          const url = window.URL.createObjectURL(new Blob([res.data]))
          // 创建一个a标签用于下载
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', '档案盒导入模板.xlsx') // 下载文件名
          document.body.appendChild(link)
          link.click()
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    importExcel() {
      this.$refs.excelUploadInput.click()
    },
    async uploadChange(event) {
      const files = event.target.files
      if (files.length > 0) {
        // 大于0，说明有文件要上传
        // 创建FormData对象
        const data = new FormData()
        // 添加文件
        data.append('file', files[0])
        // 调用接口
        await impBoxStep1(data)
          .then((res) => {
            if (res.data.code === 200) {
              this.$refs.importOneDialog.init(data, res.data.data)
            } else {
              this.$message.error(res.data.message)
            }
          })
          .catch((err) => {
            this.$message.error(err)
          })
      }
    },
    importTwo(data, props) {
      this.excelData = {
        data: data,
        props: props,
        type: 'box',
      }
      this.$refs.importTwoDialog.init(data, props, 'box')
    },
    closeImportOne() {
      this.$refs.excelUploadInput.value = ''
    },
    closeImportTwo() {
      this.$refs.excelUploadInput.value = ''
      this.$refs.importOneDialog.closeDialog()
    },
    handleAdd() {
      this.$refs.newBoxDialog.add()
    },
    handleEdit(row) {
      this.$refs.newBoxDialog.edit(row)
    },
    archivesByBoxNo(row) {
      this.$refs.archivesByBoxNo.init(row)
    },
    // 发标签
    sendTags() {
      if (this.selectionData.length == 0) {
        this.$message.warning('请选择要发标签的档案盒')
        return
      }
      // 如果勾选的数据存在rfid
      if (this.selectionData.some((item) => item.rfid)) {
        this.$message.warning('已选择档案盒中存在已发标签的档案盒，请重新选择')
        return
      }
      this.$refs.sendTagsDialog.add(this.selectionData, 'box')
      this.getTemplateTableProps()
    },
    // 获取模版需要打印的字段
    getTemplateTableProps() {
      queryBoxTemp().then((res) => {
        if (res.data.code == 200) {
          this.field = res.data.data
        }
      })
    },
    goUp() {
      if (this.selectionData.length === 0) {
        this.$message.warning('请选择要上架的档案盒')
        return
      }
      this.$router.push({
        name: 'upShelves',
        params: {
          activeName: 'box',
          selectionData: this.selectionData,
        },
      })
    },
  },
}
</script>

<style scoped></style>
